package cn.yunhe;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

/**
 * Created by zs on 2017/12/1.
 * 测试Hash结构
 */
public class Demo5 {

    @Test
    public void testHash() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);

        String key = "hash";
        Map<String, String> map = new HashMap<String, String>();
        map.put("f1", "val1");
        map.put("f2", "val2");

        //hmset命令，设置多个键值对
        redisTemplate.opsForHash().putAll(key, map);
        //hset命令，单个设值
        redisTemplate.opsForHash().put(key, "f3", "6");
        printValueForHash(redisTemplate, key, "f3");

        //hexists key field命令——是否存在
        boolean exists = redisTemplate.opsForHash().hasKey(key, "f3");
        System.out.println(exists);

        //hgetall命令——获取所有的键值对
        Map keyValMap = redisTemplate.opsForHash().entries(key);

        //hincrby命令——某一字段加上一个整数
        redisTemplate.opsForHash().increment(key, "f3", 2);
        printValueForHash(redisTemplate, key, "f3");

        //hincrbyfloat命令——加上一个浮点型
        redisTemplate.opsForHash().increment(key, "f3", 0.88);
        printValueForHash(redisTemplate, key, "f3");

        //hvals命令——获取所有的value
        List valueList = redisTemplate.opsForHash().values(key);
        System.out.println(valueList);

        //hkeys命令——获取所有的key
        Set keySet = redisTemplate.opsForHash().keys(key);
        System.out.println(keySet);

        //hmget命令——返回多个指定键的值
        List<String> fieldList = new ArrayList<String>();
        fieldList.add("f1");
        fieldList.add("f2");

        List valueList2 = redisTemplate.opsForHash().multiGet(key, fieldList);

        //hsetnx命令——不存在指定的键，才设定值
        boolean success = redisTemplate.opsForHash().putIfAbsent(key, "f4", "val4");
        System.out.println(success);

        //hdel命令——删除某个字段
        Long result = redisTemplate.opsForHash().delete(key, "f1", "f2");
        System.out.println(result);

    }


    private static void printValueForHash(RedisTemplate redisTemplate, String key, String field) {
        //相当于hget命令
        Object value = redisTemplate.opsForHash().get(key, field);
        System.out.println(value);
    }
}
